//
//  Service.swift
//  ProjectApp
//
//  Created by jack on 2021/1/8.
//

import Foundation
typealias RespHandle<T: Codable> = (_ suc: Bool, _ data: RespEntity<T>?, _ error: Error?) -> Void

/// 业务接口请求
/// - Parameters:
///   - params: 业务参数
///   - errorToast: 错误时是否进行错误toast提示
///   - hud: 是否显示请求loading
///   - handle: 业务回调
func request<T: Codable>(params: RequestParams, errorToast: Bool, hud: Bool, handle: @escaping RespHandle<T>) {
    if hud {
        showHUD()
    }
    
//    #if DEBUG
//    let localStr =  getBundleFileContentString(resource: "video", type: "json")
//    proceResponse(params: params, suc: true, resp: localStr, error: nil, errorToast: errorToast, handle: handle, responseHeader: nil)
//    return
//    #endif
    
    CPRequest(params: params) { (suc: Bool, resp: String?, error: Error?, respHeader: [AnyHashable : Any]?) in
        if hud {
            hideHUD()
        }
        proceResponse(params: params, suc: suc, resp: resp, error: error, errorToast: errorToast, handle: handle, responseHeader: respHeader)
    }
}

func proceResponse<T: Codable>(params: RequestParams, suc: Bool, resp: String?, error: Error?,errorToast:Bool, handle: @escaping RespHandle<T>, responseHeader: [AnyHashable : Any]?) {
    #if DEBUG
    // debug模式打印接口数据，方便调试和数据监听
    DPrint(message:"\n\n\n========================================\nurl:\(params.url)  \nparams:\(String(describing: params.params)) \nresp:\(String(describing: resp))\n\n\n" )
    #endif
    if suc {
        if let str = resp {
            if let json = converJsonToObj(json: str) as? [String: Any] {
                let model = RespEntity<T>(dic: json)
                if errorToast && !model.suc {
                    var msg = "业务出错"
                    if let str = model.msg {
                        msg = str
                    }
                    showToast(msg: msg)
                }
                handle(true, model, nil)
            } else {
                if errorToast {
                    showToast(msg: "数据解析错误")
                }
                handle(false, nil, error)
            }
        } else {
            if errorToast {
                showToast(msg: "请求出错")
            }
            handle(false, nil, error)
        }
    } else {
        if errorToast {
            showToast(msg: "请求出错")
        }
        handle(false, nil, error)
    }
}

func showToast(msg: String) -> Void {
    DispatchQueue.main.async {
       
    }
}

func showHUD() -> Void {
    DispatchQueue.main.async {
       
    }
}

func hideHUD() -> Void {
    DispatchQueue.main.async {
       
    }
}
